<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="400">
    <el-form
      ref="formRef"
      :inline="false"
      :model="formData"
      :rules="rules"
      class="demo-form-inline"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="商品名" prop="goodsName">
            <el-input
              v-model="formData.goodsName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="子商品名" prop="subGoodsName">
            <el-input
              v-model="formData.subGoodsName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="所属商家" prop="belongs">
            <el-input
              v-model="formData.belongs"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="详细说明" prop="detail">
            <el-input
              v-model="formData.detail"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="所属地区">
            <el-cascader
              v-model="formData.locationId",
              placeholder="请选择"
              :props="regionsProps"
              :show-all-levels="false"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="btn_group">
          <el-button @click="onCancel">取消</el-button>
          <el-button type="primary" @click="onApply">确定</el-button>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, reactive, ref, computed, watch } from "vue";
import {
  createGoods,
  updateGoods,
  selectLocationPage,
  selectSubLocations, selectGoodsById,
} from "@/network/api";
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  param: {
    type: Object,
    default: null,
  },
});

const emits = defineEmits(["update:show", "refresh"]);
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(val) {
    emits("update:show", val);
  },
});

const dialogTitle = computed(() => {
  return props.param ? "修改商品" : "增加商品";
});

watch(dialogVisible, (value) => {
  if (value) {
    resetForm();
    if (props.param) {
      formData.goodsName = props.param.goodsName;
      formData.subGoodsName = props.param.subGoodsName;
      formData.belongs = props.param.belongs;
      formData.id = props.param.id.toString();
      let location = props.param.location;
      let locationId = location.id?location.id.toString():'';
      formData.locationId = [locationId];
      while(location.parent) {
        location = location.parent;
        formData.locationId.unshift(location.id.toString());
      }
    }
    selectGoodsById({
      goodsId: props.param.id.toString(),
    }).then((res) => {
      if (res?.data) {
        formData.detail = res.data.detail;
      }
    });
  }
});
const regionsProps = {
  checkStrictly: true,
  lazy: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    console.log(node, level);
    if (level === 0) {
      selectLocationPage({
        current: 1,
        size: 1000,
      }).then((res) => {
        if (res?.data?.records?.length > 0) {
          resolve(
            res.data.records
              .filter((i) => !i.parent)
              .map((i) => {
                return {
                  value: i.id.toString(),
                  label: i.locationName,
                  leaf: false,
                };
              })
          );
        } else {
          resolve([]);
          //node.isLeaf = true;
        }
      });
    } else {
      selectSubLocations({
        parentId: node.value,
      }).then((res) => {
        if (res?.data?.length > 0) {
          resolve(
            res.data.map((i) => {
              return {
                label: i.locationName,
                value: i.id.toString(),
                leaf: false,
              };
            })
          );
        } else {
          resolve([]);
          //node.isLeaf = true;
        }
      });
    }
  },
};
const formRef = ref();
const rules = reactive({
  goodsName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  subGoodsName: [
    { required: false, message: "请输入子商品名称", trigger: "blur" },
  ],
  belongs: [{ required: false, message: "请输入所属商家", trigger: "blur" }],
  detail: [{ required: false, message: "请输入详细说明", trigger: "blur" }],
  locationId: [
    { required: false, message: "请选择所属地区", trigger: "change" },
  ],
});

const formData = reactive({
  goodsName: "",
  subGoodsName: "",
  belongs: "",
  locationId: "",
  id: "",
  detail:"",
});

const resetForm = () => {
  formData.goodsName = "";
  formData.subGoodsName = "";
  formData.belongs = "";
  formData.locationId = "";
  formData.location = "";
  formData.detail = "";
};

const onCancel = () => {
  resetForm();
  emits("update:show", false);
};
const onApply = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (props.param) {
        updateGoods({
          id: formData.id.toString(),
          goodsName: formData.goodsName,
          subGoodsName: formData.subGoodsName,
          belongs: formData.belongs,
          detail: formData.detail,
          locationId: formData.locationId?formData.locationId[formData.locationId.length - 1]:"",
        }).then((res) => {
          if (res?.code === 200) {
            ElMessage({
              message: "edit success",
              type: "success",
            });

            resetForm();
            emits("update:show", false);
            emits("refresh", true);
          } else {
            ElMessage({
              message: "edit faild",
              type: "error",
            });
          }
        });
      } else {
        createGoods({
          goodsName: formData.goodsName,
          subGoodsName: formData.subGoodsName,
          belongs: formData.belongs,
          detail: formData.detail,
          locationId: formData.locationId[formData.locationId.length - 1] ?? "",
        }).then((res) => {
          if (res?.code === 200) {
            ElMessage({
              message: "add success",
              type: "success",
            });

            resetForm();
            emits("update:show", false);
            emits("refresh", true);
          } else {
            ElMessage({
              message: "add faild",
              type: "error",
            });
          }
        });
      }
    }
  });
};
</script>
<style lang="scss" scoped>
.btn_group {
  text-align: center;
}
</style>
